<?php

namespace app\models;

use think\Db;
use think\Model;

class User extends Model
{
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created';
    protected $defaultSoftDelete = 0;


    /**
     * 资产变动变更记录
     * $type = 1 入账 2提现
     * @return void
     */
    public static function MoneyEdit($user_id, $type = 0, $money = 0, $info = '', $source = 0, $comeuser_id = 0)
    {
        if ($money != 0 && $user_id > 0) {
            $user = (new User())->where('id', $user_id)->find();
            if (empty($user)) {
                throw new \Exception("用户不存在，请重试", 100);
            }
            if ($money < 0 && $user['intergal'] < $money) {
                throw new \Exception("积分不足，请重试", 100);
            }
            $res = (new User())->where(['id' => $user['id'], 'intergal' => $user['intergal']])->setInc('intergal', $money);
            if (!$res) {
                throw new \Exception("积分修改失败，请重试", 100);
            }
            $res2 = (new UserLog())->save([
                'timeid' => time(),
                'user_id' => $user['id'],
                'comeuser_id' => $comeuser_id,
                'befores' => $user['intergal'],
                'money' => $money,
                'after' => ($user['intergal'] + $money),
                'type' => $type,
                'info' => $info,
                'source' => $source
            ]);
            if (!$res2) {
                throw new \Exception("积分记录失败，请重试", 100);
            }
        }
    }
}